package wjl.java.base.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

public class OfficeUtil {
    public static void main( String[] args ) throws Exception {
        System.out.println( System.getProperty( "user.dir" ) );
    }

    /**
     * 文档转PDF
     * 
     * @param srcPath 源文件路径
     * @param destPath pdf文件目录
     * @throws Exception
     */
    public static void officeToPDF( String libreOfficeHome, String srcPath, String destPath )
            throws Exception {

        if ( StringUtil.isNullStr( libreOfficeHome ) ){
            libreOfficeHome = "C:/Program Files/LibreOffice";
            File libreOfficeFile = new File( libreOfficeHome );
            if ( !libreOfficeFile.exists() || !libreOfficeFile.isDirectory() ){
                // 下载libreOffice,并解压到默认目录
                File executeFile = new File( System.getProperty( "user.dir" ) + File.separator
                        + "LibreOffice_7.0.1_Win_x64.msi" );
                if ( !executeFile.exists() ){
                    String libreOfficeUrl =
                            "https://mirrors.cloud.tencent.com/libreoffice/libreoffice/stable/7.0.1/win/x86_64/LibreOffice_7.0.1_Win_x64.msi";
                    byte[] data           = WebUtil.downloadFile( libreOfficeUrl );
                    FileUtil.writeFileByBytes( data, System.getProperty( "user.dir" ),
                            "LibreOffice_7.0.1_Win_x64.msi", false );
                }
                List<String> cmdList = new ArrayList<>();
                cmdList.add( "msiexec" );
                cmdList.add( "/package" );
                cmdList.add( System.getProperty( "user.dir" ) + File.separator
                        + "LibreOffice_7.0.1_Win_x64.msi" );
                ProcessBuilder librePB = new ProcessBuilder( cmdList );
                librePB.directory( new File( System.getProperty( "user.dir" ) ) );
                Process process = librePB.start();
                process.waitFor();
                boolean success = process.exitValue() == 0;
                if ( !success ){
                    throw new Exception( "execute LibreOffice failed..." );
                }
            }
        }
        List<String> cmdList = new ArrayList<>();
        cmdList.add( libreOfficeHome + "/program/soffice" );
        cmdList.add( "--headles s" );
        cmdList.add( "--convert-to" );
        cmdList.add( "pdf" );
        cmdList.add( srcPath );
        cmdList.add( "--outdir" );
        cmdList.add( destPath );
        ProcessBuilder pb = new ProcessBuilder( cmdList );
        pb.directory( new File( libreOfficeHome + "/program" ) );
        Process process = pb.start();
        process.waitFor();
        boolean success = process.exitValue() == 0;
        if ( !success ){
            throw new Exception( "Convert failed" );
        }
    }

    /**
     * pdf转图片
     * 
     * @param srcPath
     * @param destDirPath
     * @throws IOException
     */
    public static void pdfToPng( String srcPath, String destDirPath ) throws IOException {
        // 再把pdf转换成png
        File       pdfFile = new File( srcPath );
        PDDocument pdf     = null;
        try{
            pdf = PDDocument.load( pdfFile );
            PDFRenderer renderer  = new PDFRenderer( pdf );
            int         pageCount = pdf.getNumberOfPages();
            for ( int i = 0; i < pageCount; ++i ){
                File pngFile = new File( destDirPath, (i + 1) + ".png" );
                // 方式1,第二个参数是设置缩放比(即像素) renderImageWithDPI(i, 296);
                // 方式2,第二个参数是设置缩放比(即像素) 第二个参数越大生成图片分辨率越高，转换时间也就越长
                BufferedImage image = renderer.renderImage( i, 1.25f );
                ImageIO.write( image, "PNG", pngFile );
            }
        } finally{
            if ( pdf != null )
                pdf.close();
        }
    }
}
